<template>
	<view class="invoice-page">
		<!-- <u-navbar
			title="发票开具"
			:autoBack="true"
			rightText="开具历史"
			:titleStyle="{fontWeight: 700}"
			@rightClick="rightClick"
		>
		</u-navbar> --> 
		
		<view class="tab-header">
			<text :class="['tab-item', (formData.status === -1 || formData.status === '') && 'active']" @click="switchTab(-1)">全部</text>
			<text :class="['tab-item', formData.status === 0 && 'active']" @click="switchTab(0)">未开票</text>
			<text :class="['tab-item', formData.status === 1 && 'active']" @click="switchTab(1)">申请中</text>
			<text :class="['tab-item', formData.status === 2 && 'active']" @click="switchTab(2)">已开票</text>
		</view>
		
		<view class="invoice-list">
			<view v-for="(item, index) in invoiceList" :key="index" class="invoice-item">
				<view class="title flex flex-between">
					<view class="order-number">{{ item.orderNumber }}</view>
					<view class="payment-time">支付时间: {{ item.payTime | formatTime }}</view>
				</view>
				
				<view class="device-info flex">
					<u-checkbox-group>
						<u-checkbox 
							shape="circle" 
							:checked="item.selected" 
							v-if="item.status === 3"
							@change="toggleCheck(index)"
						/>
					</u-checkbox-group>
					<view class="info-content" @click="showDetail(index)">
						<view style="font-size: 28rpx;">{{ item.stationName }}</view>
						<view>已充电量: {{ item.chargedEnergy }}度</view>
						<view>充电时长: {{ item.chargingDuration | formatMinutes }}</view>
						<view>终端名称: {{ item.terminalName }}</view>
						<view>终端编码: {{ item.terminalId }}</view>
					</view>
					<view class="price flex flex-column" @click="showDetail(index)">
						<text class="status" :class="item.invoiceStatus == 2 ? 'issued' : 'not-issued'">
							{{ item.invoiceStatus == 2 ? '已开票' : (item.invoiceStatus == 1 ? '开票中' : '未开票') }}
						</text>
						<view class="flex flex-column">
							<text class="amount">{{ item.chargedAmount }}元</text>
							<text class="label">实付金额</text>
						</view>
					</view>
				</view>
			</view>
		
			<!-- 数据为空 -->
			<view class="empty" v-if="invoiceList.length == 0">
				<u-empty mode="data"></u-empty>
			</view>
			
			<!-- 加载更多 -->
			<u-loadmore v-if="invoiceList && invoiceList.length > 0" :status="loadMoreStatus" />
		</view>
		
		<view class="bottom-bar">
			<view class="total">开票金额：<text class="price">{{ totalAmount }}</text></view>
			<button 
				class="next-btn" 
				:class="!hasSelected && 'disabled'" 
				:disabled="!hasSelected"
				@click="goToApply"
			>
				下一步
			</button>
		</view>
	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex'
	import { formatWeChatTime, formatMinutes } from '@/utils/index.js'
	export default {
		data() {
			return {
				activeTab: -1,
				invoiceList: [],
				formData: {
					pageNo: 1,
					pageSize: 15,
					status: '', // 3已支付（未开票），已开票4
				},
				isLoading: false,
				isFinished: false,
			}
		},
		computed: {
			//引入store全局变量
			...mapState(['loginState', 'userInfo']),
			
			loadMoreStatus() {
				if (this.isLoading) return 'loading'
				if (this.isFinished) return 'nomore'
				return 'loadmore'
			},
			
			totalAmount() {
				return this.invoiceList
					.filter(item => item.status === 3 && item.selected)
					.reduce((sum, item) => sum + parseFloat(item.chargedAmount), 0)
					.toFixed(2)
			},
			
			hasSelected() {
				return this.invoiceList.some(item => item.status === 3 && item.selected)
			}
		},
		onLoad() {
			this.getlist();
		},
		onReachBottom() {
			this.getlist();
		},
		methods: {
			
			//订单列表
			getlist() {
				if (this.isFinished || this.isLoading) return
				this.isLoading = true
				this.$http_api.invoiceOrderList(this.formData).then((res) => {
					const { records, total } = res;
					// 初始化selected字段
					const processedRecords = records.map(item => ({
						...item,
						selected: false
					}));
					
					this.invoiceList = this.formData.pageNo === 1 
						? processedRecords 
						: [...this.invoiceList, ...processedRecords];
					this.isFinished = records.length < 15
					this.formData.pageNo++
				}).finally(() => {
					this.isLoading = false
				})
			},
			
			goToApply() {
				const selectedIds = this.invoiceList
					.filter(item => item.status === 3 && item.selected)
					.map(item => item.id);
				
				if (selectedIds.length === 0) {
					uni.showToast({ title: '请选择要开票的订单', icon: 'none' });
					return;
				}
				
				uni.navigateTo({
					url: '/pages/user/users/invoice/apply?id=' + selectedIds.join(','),
					success: () => {
						this.switchTab(this.activeTab)
					}
				});
			},
			
			showDetail(index) {
				const item = this.invoiceList[index];
				uni.navigateTo({
					url: '/pages/order/invoice-detail?id=' + item.id
				})
			},
			
			rightClick() {
				uni.navigateTo({
					url: '/pages/user/users/invoice/history'
				})
			},
			
			// 切换导航
			switchTab(index) {
				this.isFinished = false;
				this.isLoading = false;
				this.invoiceList = [];
				this.formData.status = index == -1 ? '' : parseInt(index);
				this.formData.pageNo = 1;
				this.getlist();
			},
			
			// 新增复选框切换方法
			toggleCheck(index) {
				const item = this.invoiceList[index];
				// 只有未开票订单可以切换选中状态
				if (item.status === 3) {
					this.$set(this.invoiceList, index, {
						...item,
						selected: !item.selected
					});
				}
			}
		},
		filters: {
			formatTime(timestamp) {
				if (!timestamp) return '';
				    
				    // 确保是数字类型的时间戳
				    const time = new Date(Number(timestamp));
				    
				    // 格式化为年月日时分秒
				    const year = time.getFullYear();
				    const month = (time.getMonth() + 1).toString().padStart(2, '0');
				    const day = time.getDate().toString().padStart(2, '0');
				    const hours = time.getHours().toString().padStart(2, '0');
				    const minutes = time.getMinutes().toString().padStart(2, '0');
				    const seconds = time.getSeconds().toString().padStart(2, '0');
				    
				    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			formatMinutes(minute) {
				return formatMinutes(minute)
			}
		}
	}
</script>

<style scoped lang="scss">
	.invoice-page {
		padding-bottom: calc(88rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(88rpx + env(safe-area-inset-bottom));
		
		.tab-header {
			display: flex;
			background: #fff;
			padding: 20rpx 0;
			position: sticky;
			top: var(--window-top);
			z-index: 100;
			
			.tab-item {
				flex: 1;
				text-align: center;
				position: relative;
				color: #666;
				
				&.active {
					color: #42E0A2;
					font-weight: bold;
					
					&::after {
						content: '';
						position: absolute;
						bottom: -20rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 40rpx;
						height: 8rpx;
						background: #42E0A2;
						border-radius: 69rpx;
					}
				}
			}
		}
		
		.invoice-list {
			padding: 20rpx;
			
			.invoice-item {
				background: #fff;
				border-radius: 12rpx;
				padding: 20rpx;
				margin-bottom: 20rpx;
				
				.title {
					border-bottom: 1rpx solid #eee;
					margin-bottom: 20rpx;
					padding-bottom: 10rpx;
				}
				
				.order-number, .payment-time {
					color: #666;
					font-size: 24rpx;
					margin-bottom: 10rpx;
				}
				
				.device-info {
					position: relative;
					
					.info-content {
						flex: 1;
						margin: 0 20rpx;
						font-size: 24rpx;
						line-height: 1.8;
						font-family: "PINGFANG";
						
						&:first-child {
							color: #333;
						}
						
						view:not(:first-child) {
							color: #777777;
							font-size: 22rpx;
						}
					}
					
					.price {
						text-align: right;
						height: 140rpx;
						justify-content: space-between;
						
						.status {
							display: block;
							font-size: 24rpx;
							margin-bottom: 10rpx;
							position: absolute;
							right: 0;
							top: 5rpx;
							
							&.issued {
								color: #999;
							}
							
							&.not-issued {
								color: #ff6b00;
							}
						}
						
						.amount {
							color: #FC0A01;
							font-size: 32rpx;
							font-weight: 600;
							font-family: "PINGFANG";
							margin-top: 60rpx;
						}
						
						.label {
							font-weight: 400;
							font-size: 22rpx;
							color: #333333;
							font-family: "PINGFANG";
						}
					}
				}
			}
		}
		
		.bottom-bar {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background: #fff;
			display: flex;
			align-items: center;
			padding: 20rpx;
			padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
			padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
			
			.total {
				flex: 1;
				font-size: 28rpx;
				
				.price {
					color: #ff6b00;
					font-size: 36rpx;
				}
			}
			
			.next-btn {
				background: #1C6EFB;
				color: #fff;
				padding: 0rpx 60rpx;
				border-radius: 100rpx;
				font-size: 28rpx;
			}
			
			.next-btn.disabled {
				background: #ccc !important;
				cursor: not-allowed;
			}
		}
	}
</style>